﻿#region Using directives

using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;

using Pharmacy.Entities;
using Pharmacy.Data;

#endregion

namespace Pharmacy.Data.Bases
{	
	///<summary>
	/// This class is the base class for any <see cref="PrescriptionProviderBase"/> implementation.
	/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
	///</summary>
	public abstract partial class PrescriptionProviderBaseCore : EntityProviderBase<Pharmacy.Entities.Prescription, Pharmacy.Entities.PrescriptionKey>
	{		
		#region Get from Many To Many Relationship Functions
		#endregion	
		
		#region Delete Methods

		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to delete.</param>
		/// <returns>Returns true if operation suceeded.</returns>
		public override bool Delete(TransactionManager transactionManager, Pharmacy.Entities.PrescriptionKey key)
		{
			return Delete(transactionManager, key.PrescriptionId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_prescriptionId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public bool Delete(System.String _prescriptionId)
		{
			return Delete(null, _prescriptionId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_prescriptionId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public abstract bool Delete(TransactionManager transactionManager, System.String _prescriptionId);		
		
		#endregion Delete Methods
		
		#region Get By Foreign Key Functions
	
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_Prescription_WebUser key.
		///		FK_Prescription_WebUser Description: 
		/// </summary>
		/// <param name="_salesPerson"></param>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Prescription objects.</returns>
		public TList<Prescription> GetBySalesPerson(System.String _salesPerson)
		{
			int count = -1;
			return GetBySalesPerson(_salesPerson, 0,int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_Prescription_WebUser key.
		///		FK_Prescription_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_salesPerson"></param>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Prescription objects.</returns>
		/// <remarks></remarks>
		public TList<Prescription> GetBySalesPerson(TransactionManager transactionManager, System.String _salesPerson)
		{
			int count = -1;
			return GetBySalesPerson(transactionManager, _salesPerson, 0, int.MaxValue, out count);
		}
		
			/// <summary>
		/// 	Gets rows from the datasource based on the FK_Prescription_WebUser key.
		///		FK_Prescription_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_salesPerson"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Prescription objects.</returns>
		public TList<Prescription> GetBySalesPerson(TransactionManager transactionManager, System.String _salesPerson, int start, int pageLength)
		{
			int count = -1;
			return GetBySalesPerson(transactionManager, _salesPerson, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_Prescription_WebUser key.
		///		fkPrescriptionWebUser Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_salesPerson"></param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Prescription objects.</returns>
		public TList<Prescription> GetBySalesPerson(System.String _salesPerson, int start, int pageLength)
		{
			int count =  -1;
			return GetBySalesPerson(null, _salesPerson, start, pageLength,out count);	
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_Prescription_WebUser key.
		///		fkPrescriptionWebUser Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_salesPerson"></param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Prescription objects.</returns>
		public TList<Prescription> GetBySalesPerson(System.String _salesPerson, int start, int pageLength,out int count)
		{
			return GetBySalesPerson(null, _salesPerson, start, pageLength, out count);	
		}
						
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_Prescription_WebUser key.
		///		FK_Prescription_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_salesPerson"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns a typed collection of Pharmacy.Entities.Prescription objects.</returns>
		public abstract TList<Prescription> GetBySalesPerson(TransactionManager transactionManager, System.String _salesPerson, int start, int pageLength, out int count);
		
		#endregion

		#region Get By Index Functions
		
		/// <summary>
		/// 	Gets a row from the DataSource based on its primary key.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to retrieve.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <returns>Returns an instance of the Entity class.</returns>
		public override Pharmacy.Entities.Prescription Get(TransactionManager transactionManager, Pharmacy.Entities.PrescriptionKey key, int start, int pageLength)
		{
			return GetByPrescriptionId(transactionManager, key.PrescriptionId, start, pageLength);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the primary key PK_Prescription index.
		/// </summary>
		/// <param name="_prescriptionId"></param>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Prescription"/> class.</returns>
		public Pharmacy.Entities.Prescription GetByPrescriptionId(System.String _prescriptionId)
		{
			int count = -1;
			return GetByPrescriptionId(null,_prescriptionId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Prescription index.
		/// </summary>
		/// <param name="_prescriptionId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Prescription"/> class.</returns>
		public Pharmacy.Entities.Prescription GetByPrescriptionId(System.String _prescriptionId, int start, int pageLength)
		{
			int count = -1;
			return GetByPrescriptionId(null, _prescriptionId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Prescription index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_prescriptionId"></param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Prescription"/> class.</returns>
		public Pharmacy.Entities.Prescription GetByPrescriptionId(TransactionManager transactionManager, System.String _prescriptionId)
		{
			int count = -1;
			return GetByPrescriptionId(transactionManager, _prescriptionId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Prescription index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_prescriptionId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Prescription"/> class.</returns>
		public Pharmacy.Entities.Prescription GetByPrescriptionId(TransactionManager transactionManager, System.String _prescriptionId, int start, int pageLength)
		{
			int count = -1;
			return GetByPrescriptionId(transactionManager, _prescriptionId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Prescription index.
		/// </summary>
		/// <param name="_prescriptionId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Prescription"/> class.</returns>
		public Pharmacy.Entities.Prescription GetByPrescriptionId(System.String _prescriptionId, int start, int pageLength, out int count)
		{
			return GetByPrescriptionId(null, _prescriptionId, start, pageLength, out count);
		}
		
				
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Prescription index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_prescriptionId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns an instance of the <see cref="Pharmacy.Entities.Prescription"/> class.</returns>
		public abstract Pharmacy.Entities.Prescription GetByPrescriptionId(TransactionManager transactionManager, System.String _prescriptionId, int start, int pageLength, out int count);
						
		#endregion "Get By Index Functions"
	
		#region Custom Methods
		
		
		#endregion

		#region Helper Functions	
		
		/// <summary>
		/// Fill a TList&lt;Prescription&gt; From a DataReader.
		/// </summary>
		/// <param name="reader">Datareader</param>
		/// <param name="rows">The collection to fill</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">number of rows.</param>
		/// <returns>a <see cref="TList&lt;Prescription&gt;"/></returns>
		public static TList<Prescription> Fill(IDataReader reader, TList<Prescription> rows, int start, int pageLength)
		{
			NetTiersProvider currentProvider = DataRepository.Provider;
            bool useEntityFactory = currentProvider.UseEntityFactory;
            bool enableEntityTracking = currentProvider.EnableEntityTracking;
            LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy;
			Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType;
			
			// advance to the starting row
			for (int i = 0; i < start; i++)
			{
				if (!reader.Read())
				return rows; // not enough rows, just return
			}
			for (int i = 0; i < pageLength; i++)
			{
				if (!reader.Read())
					break; // we are done
					
				string key = null;
				
				Pharmacy.Entities.Prescription c = null;
				if (useEntityFactory)
				{
					key = new System.Text.StringBuilder("Prescription")
					.Append("|").Append((System.String)reader[((int)PrescriptionColumn.PrescriptionId - 1)]).ToString();
					c = EntityManager.LocateOrCreate<Prescription>(
					key.ToString(), // EntityTrackingKey
					"Prescription",  //Creational Type
					entityCreationFactoryType,  //Factory used to create entity
					enableEntityTracking); // Track this entity?
				}
				else
				{
					c = new Pharmacy.Entities.Prescription();
				}
				
				if (!enableEntityTracking ||
					c.EntityState == EntityState.Added ||
					(enableEntityTracking &&
					
						(
							(currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) ||
							(currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged)
						)
					))
				{
					c.SuppressEntityEvents = true;
					c.PrescriptionId = (System.String)reader[((int)PrescriptionColumn.PrescriptionId - 1)];
					c.OriginalPrescriptionId = c.PrescriptionId;
					c.PatientCode = (System.String)reader[((int)PrescriptionColumn.PatientCode - 1)];
					c.PatientName = (System.String)reader[((int)PrescriptionColumn.PatientName - 1)];
					c.DeliveryDate = (System.DateTime)reader[((int)PrescriptionColumn.DeliveryDate - 1)];
					c.CreateDate = (System.DateTime)reader[((int)PrescriptionColumn.CreateDate - 1)];
					c.Address = (reader.IsDBNull(((int)PrescriptionColumn.Address - 1)))?null:(System.String)reader[((int)PrescriptionColumn.Address - 1)];
					c.DateOfBirth = (reader.IsDBNull(((int)PrescriptionColumn.DateOfBirth - 1)))?null:(System.DateTime?)reader[((int)PrescriptionColumn.DateOfBirth - 1)];
					c.PrescribingDoctor = (reader.IsDBNull(((int)PrescriptionColumn.PrescribingDoctor - 1)))?null:(System.String)reader[((int)PrescriptionColumn.PrescribingDoctor - 1)];
					c.Vat = (System.Decimal)reader[((int)PrescriptionColumn.Vat - 1)];
					c.Amount = (System.Decimal)reader[((int)PrescriptionColumn.Amount - 1)];
					c.CoveredTotal = (System.Decimal)reader[((int)PrescriptionColumn.CoveredTotal - 1)];
					c.PayableAmount = (System.Decimal)reader[((int)PrescriptionColumn.PayableAmount - 1)];
					c.TotalAmount = (System.Decimal)reader[((int)PrescriptionColumn.TotalAmount - 1)];
					c.SalesPerson = (System.String)reader[((int)PrescriptionColumn.SalesPerson - 1)];
					c.ExchangeRate = (reader.IsDBNull(((int)PrescriptionColumn.ExchangeRate - 1)))?null:(System.Int32?)reader[((int)PrescriptionColumn.ExchangeRate - 1)];
					c.IsVoid = (System.Boolean)reader[((int)PrescriptionColumn.IsVoid - 1)];
					c.Remark = (reader.IsDBNull(((int)PrescriptionColumn.Remark - 1)))?null:(System.String)reader[((int)PrescriptionColumn.Remark - 1)];
					c.EntityTrackingKey = key;
					c.AcceptChanges();
					c.SuppressEntityEvents = false;
				}
				rows.Add(c);
			}
		return rows;
		}		
		/// <summary>
		/// Refreshes the <see cref="Pharmacy.Entities.Prescription"/> object from the <see cref="IDataReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader"/> to read from.</param>
		/// <param name="entity">The <see cref="Pharmacy.Entities.Prescription"/> object to refresh.</param>
		public static void RefreshEntity(IDataReader reader, Pharmacy.Entities.Prescription entity)
		{
			if (!reader.Read()) return;
			
			entity.PrescriptionId = (System.String)reader[((int)PrescriptionColumn.PrescriptionId - 1)];
			entity.OriginalPrescriptionId = (System.String)reader["PrescriptionID"];
			entity.PatientCode = (System.String)reader[((int)PrescriptionColumn.PatientCode - 1)];
			entity.PatientName = (System.String)reader[((int)PrescriptionColumn.PatientName - 1)];
			entity.DeliveryDate = (System.DateTime)reader[((int)PrescriptionColumn.DeliveryDate - 1)];
			entity.CreateDate = (System.DateTime)reader[((int)PrescriptionColumn.CreateDate - 1)];
			entity.Address = (reader.IsDBNull(((int)PrescriptionColumn.Address - 1)))?null:(System.String)reader[((int)PrescriptionColumn.Address - 1)];
			entity.DateOfBirth = (reader.IsDBNull(((int)PrescriptionColumn.DateOfBirth - 1)))?null:(System.DateTime?)reader[((int)PrescriptionColumn.DateOfBirth - 1)];
			entity.PrescribingDoctor = (reader.IsDBNull(((int)PrescriptionColumn.PrescribingDoctor - 1)))?null:(System.String)reader[((int)PrescriptionColumn.PrescribingDoctor - 1)];
			entity.Vat = (System.Decimal)reader[((int)PrescriptionColumn.Vat - 1)];
			entity.Amount = (System.Decimal)reader[((int)PrescriptionColumn.Amount - 1)];
			entity.CoveredTotal = (System.Decimal)reader[((int)PrescriptionColumn.CoveredTotal - 1)];
			entity.PayableAmount = (System.Decimal)reader[((int)PrescriptionColumn.PayableAmount - 1)];
			entity.TotalAmount = (System.Decimal)reader[((int)PrescriptionColumn.TotalAmount - 1)];
			entity.SalesPerson = (System.String)reader[((int)PrescriptionColumn.SalesPerson - 1)];
			entity.ExchangeRate = (reader.IsDBNull(((int)PrescriptionColumn.ExchangeRate - 1)))?null:(System.Int32?)reader[((int)PrescriptionColumn.ExchangeRate - 1)];
			entity.IsVoid = (System.Boolean)reader[((int)PrescriptionColumn.IsVoid - 1)];
			entity.Remark = (reader.IsDBNull(((int)PrescriptionColumn.Remark - 1)))?null:(System.String)reader[((int)PrescriptionColumn.Remark - 1)];
			entity.AcceptChanges();
		}
		
		/// <summary>
		/// Refreshes the <see cref="Pharmacy.Entities.Prescription"/> object from the <see cref="DataSet"/>.
		/// </summary>
		/// <param name="dataSet">The <see cref="DataSet"/> to read from.</param>
		/// <param name="entity">The <see cref="Pharmacy.Entities.Prescription"/> object.</param>
		public static void RefreshEntity(DataSet dataSet, Pharmacy.Entities.Prescription entity)
		{
			DataRow dataRow = dataSet.Tables[0].Rows[0];
			
			entity.PrescriptionId = (System.String)dataRow["PrescriptionID"];
			entity.OriginalPrescriptionId = (System.String)dataRow["PrescriptionID"];
			entity.PatientCode = (System.String)dataRow["PatientCode"];
			entity.PatientName = (System.String)dataRow["PatientName"];
			entity.DeliveryDate = (System.DateTime)dataRow["DeliveryDate"];
			entity.CreateDate = (System.DateTime)dataRow["CreateDate"];
			entity.Address = Convert.IsDBNull(dataRow["Address"]) ? null : (System.String)dataRow["Address"];
			entity.DateOfBirth = Convert.IsDBNull(dataRow["DateOfBirth"]) ? null : (System.DateTime?)dataRow["DateOfBirth"];
			entity.PrescribingDoctor = Convert.IsDBNull(dataRow["PrescribingDoctor"]) ? null : (System.String)dataRow["PrescribingDoctor"];
			entity.Vat = (System.Decimal)dataRow["VAT"];
			entity.Amount = (System.Decimal)dataRow["Amount"];
			entity.CoveredTotal = (System.Decimal)dataRow["CoveredTotal"];
			entity.PayableAmount = (System.Decimal)dataRow["PayableAmount"];
			entity.TotalAmount = (System.Decimal)dataRow["TotalAmount"];
			entity.SalesPerson = (System.String)dataRow["SalesPerson"];
			entity.ExchangeRate = Convert.IsDBNull(dataRow["ExchangeRate"]) ? null : (System.Int32?)dataRow["ExchangeRate"];
			entity.IsVoid = (System.Boolean)dataRow["IsVoid"];
			entity.Remark = Convert.IsDBNull(dataRow["Remark"]) ? null : (System.String)dataRow["Remark"];
			entity.AcceptChanges();
		}
		#endregion 
		
		#region DeepLoad Methods
		/// <summary>
		/// Deep Loads the <see cref="IEntity"/> object with criteria based of the child 
		/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
		/// </summary>
		/// <remarks>
		/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
		/// </remarks>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">The <see cref="Pharmacy.Entities.Prescription"/> object to load.</param>
		/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
		/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
		/// <param name="childTypes">Pharmacy.Entities.Prescription Property Collection Type Array To Include or Exclude from Load</param>
		/// <param name="innerList">A collection of child types for easy access.</param>
	    /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
	    /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
		public override void DeepLoad(TransactionManager transactionManager, Pharmacy.Entities.Prescription entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
		{
			if(entity == null)
				return;

			#region SalesPersonSource	
			if (CanDeepLoad(entity, "WebUser|SalesPersonSource", deepLoadType, innerList) 
				&& entity.SalesPersonSource == null)
			{
				object[] pkItems = new object[1];
				pkItems[0] = entity.SalesPerson;
				WebUser tmpEntity = EntityManager.LocateEntity<WebUser>(EntityLocator.ConstructKeyFromPkItems(typeof(WebUser), pkItems), DataRepository.Provider.EnableEntityTracking);
				if (tmpEntity != null)
					entity.SalesPersonSource = tmpEntity;
				else
					entity.SalesPersonSource = DataRepository.WebUserProvider.GetByUserId(transactionManager, entity.SalesPerson);		
				
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'SalesPersonSource' loaded. key " + entity.EntityTrackingKey);
				#endif 
				
				if (deep && entity.SalesPersonSource != null)
				{
					innerList.SkipChildren = true;
					DataRepository.WebUserProvider.DeepLoad(transactionManager, entity.SalesPersonSource, deep, deepLoadType, childTypes, innerList);
					innerList.SkipChildren = false;
				}
					
			}
			#endregion SalesPersonSource
			
			//used to hold DeepLoad method delegates and fire after all the local children have been loaded.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
			// Deep load child collections  - Call GetByPrescriptionId methods when available
			
			#region PrescriptionVoid
			// RelationshipType.OneToOne
			if (CanDeepLoad(entity, "PrescriptionVoid|PrescriptionVoid", deepLoadType, innerList))
			{
				entity.PrescriptionVoid = DataRepository.PrescriptionVoidProvider.GetByPrescriptionId(transactionManager, entity.PrescriptionId);
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'PrescriptionVoid' loaded. key " + entity.EntityTrackingKey);
				#endif 

				if (deep && entity.PrescriptionVoid != null)
				{
					deepHandles.Add("PrescriptionVoid",
						new KeyValuePair<Delegate, object>((DeepLoadSingleHandle< PrescriptionVoid >) DataRepository.PrescriptionVoidProvider.DeepLoad,
						new object[] { transactionManager, entity.PrescriptionVoid, deep, deepLoadType, childTypes, innerList }
					));
				}
			}
			#endregion 
			
			
			
			#region PrescriptionDetailCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<PrescriptionDetail>|PrescriptionDetailCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'PrescriptionDetailCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.PrescriptionDetailCollection = DataRepository.PrescriptionDetailProvider.GetByPrescriptionId(transactionManager, entity.PrescriptionId);

				if (deep && entity.PrescriptionDetailCollection.Count > 0)
				{
					deepHandles.Add("PrescriptionDetailCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<PrescriptionDetail>) DataRepository.PrescriptionDetailProvider.DeepLoad,
						new object[] { transactionManager, entity.PrescriptionDetailCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			//Fire all DeepLoad Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			deepHandles = null;
		}
		
		#endregion 
		
		#region DeepSave Methods

		/// <summary>
		/// Deep Save the entire object graph of the Pharmacy.Entities.Prescription object with criteria based of the child 
		/// Type property array and DeepSaveType.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entity">Pharmacy.Entities.Prescription instance</param>
		/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
		/// <param name="childTypes">Pharmacy.Entities.Prescription Property Collection Type Array To Include or Exclude from Save</param>
		/// <param name="innerList">A Hashtable of child types for easy access.</param>
		public override bool DeepSave(TransactionManager transactionManager, Pharmacy.Entities.Prescription entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
		{	
			if (entity == null)
				return false;
							
			#region Composite Parent Properties
			//Save Source Composite Properties, however, don't call deep save on them.  
			//So they only get saved a single level deep.
			
			#region SalesPersonSource
			if (CanDeepSave(entity, "WebUser|SalesPersonSource", deepSaveType, innerList) 
				&& entity.SalesPersonSource != null)
			{
				DataRepository.WebUserProvider.Save(transactionManager, entity.SalesPersonSource);
				entity.SalesPerson = entity.SalesPersonSource.UserId;
			}
			#endregion 
			#endregion Composite Parent Properties

			// Save Root Entity through Provider
			if (!entity.IsDeleted)
				this.Save(transactionManager, entity);
			
			//used to hold DeepSave method delegates and fire after all the local children have been saved.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();

			#region PrescriptionVoid
			if (CanDeepSave(entity.PrescriptionVoid, "PrescriptionVoid|PrescriptionVoid", deepSaveType, innerList))
			{

				if (entity.PrescriptionVoid != null)
				{
					// update each child parent id with the real parent id (mostly used on insert)

					entity.PrescriptionVoid.PrescriptionId = entity.PrescriptionId;
					//DataRepository.PrescriptionVoidProvider.Save(transactionManager, entity.PrescriptionVoid);
					deepHandles.Add("PrescriptionVoid",
						new KeyValuePair<Delegate, object>((DeepSaveSingleHandle< PrescriptionVoid >) DataRepository.PrescriptionVoidProvider.DeepSave,
						new object[] { transactionManager, entity.PrescriptionVoid, deepSaveType, childTypes, innerList }
					));
				}
			} 
			#endregion 
	
			#region List<PrescriptionDetail>
				if (CanDeepSave(entity.PrescriptionDetailCollection, "List<PrescriptionDetail>|PrescriptionDetailCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(PrescriptionDetail child in entity.PrescriptionDetailCollection)
					{
						if(child.PrescriptionIdSource != null)
						{
							child.PrescriptionId = child.PrescriptionIdSource.PrescriptionId;
						}
						else
						{
							child.PrescriptionId = entity.PrescriptionId;
						}

					}

					if (entity.PrescriptionDetailCollection.Count > 0 || entity.PrescriptionDetailCollection.DeletedItems.Count > 0)
					{
						//DataRepository.PrescriptionDetailProvider.Save(transactionManager, entity.PrescriptionDetailCollection);
						
						deepHandles.Add("PrescriptionDetailCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< PrescriptionDetail >) DataRepository.PrescriptionDetailProvider.DeepSave,
							new object[] { transactionManager, entity.PrescriptionDetailCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
			//Fire all DeepSave Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			
			// Save Root Entity through Provider, if not already saved in delete mode
			if (entity.IsDeleted)
				this.Save(transactionManager, entity);
				

			deepHandles = null;
						
			return true;
		}
		#endregion
	} // end class
	
	#region PrescriptionChildEntityTypes
	
	///<summary>
	/// Enumeration used to expose the different child entity types 
	/// for child properties in <c>Pharmacy.Entities.Prescription</c>
	///</summary>
	public enum PrescriptionChildEntityTypes
	{
		
		///<summary>
		/// Composite Property for <c>WebUser</c> at SalesPersonSource
		///</summary>
		[ChildEntityType(typeof(WebUser))]
		WebUser,
			///<summary>
		/// Entity <c>PrescriptionVoid</c> as OneToOne for PrescriptionVoid
		///</summary>
		[ChildEntityType(typeof(PrescriptionVoid))]
		PrescriptionVoid,

		///<summary>
		/// Collection of <c>Prescription</c> as OneToMany for PrescriptionDetailCollection
		///</summary>
		[ChildEntityType(typeof(TList<PrescriptionDetail>))]
		PrescriptionDetailCollection,
	}
	
	#endregion PrescriptionChildEntityTypes
	
	#region PrescriptionFilterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;PrescriptionColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Prescription"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PrescriptionFilterBuilder : SqlFilterBuilder<PrescriptionColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PrescriptionFilterBuilder class.
		/// </summary>
		public PrescriptionFilterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PrescriptionFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PrescriptionFilterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PrescriptionFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PrescriptionFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PrescriptionFilterBuilder
	
	#region PrescriptionParameterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;PrescriptionColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Prescription"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PrescriptionParameterBuilder : ParameterizedSqlFilterBuilder<PrescriptionColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PrescriptionParameterBuilder class.
		/// </summary>
		public PrescriptionParameterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PrescriptionParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PrescriptionParameterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PrescriptionParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PrescriptionParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PrescriptionParameterBuilder
	
	#region PrescriptionSortBuilder
    
    /// <summary>
    /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;PrescriptionColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Prescription"/> object.
    /// </summary>
    [CLSCompliant(true)]
    public class PrescriptionSortBuilder : SqlSortBuilder<PrescriptionColumn>
    {
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PrescriptionSqlSortBuilder class.
		/// </summary>
		public PrescriptionSortBuilder() : base() { }

		#endregion Constructors

    }    
    #endregion PrescriptionSortBuilder
	
} // end namespace
